package com.fakeDYChat.common.common.event.listener;

import com.fakeDYChat.common.common.event.UserOnlineEvent;
import com.fakeDYChat.common.common.event.UserRegisterEvent;
import com.fakeDYChat.common.user.dao.UserDao;
import com.fakeDYChat.common.user.domain.entity.User;
import com.fakeDYChat.common.user.domain.enums.ActiveStatusEnum;
import com.fakeDYChat.common.user.domain.enums.IdempotentEnum;
import com.fakeDYChat.common.user.domain.enums.ItemEnum;
import com.fakeDYChat.common.user.service.IUserBackpackService;
import com.fakeDYChat.common.user.service.IpService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.event.TransactionPhase;
import org.springframework.transaction.event.TransactionalEventListener;

import java.util.Optional;

@Service
public class UserOnlineListener {

    private final UserDao userDao;
    private final IpService ipService;

    public UserOnlineListener(UserDao userDao, IpService ipService) {
        this.userDao = userDao;
        this.ipService = ipService;
    }

    /**
     * 用于用户上线的数据库信息更新
     *
     * @param userRegisterEvent 用户上线事件
     * @author Tang
     * @date 2024/1/4 16:11
     **/
    @Async
    @TransactionalEventListener(classes = UserOnlineEvent.class, phase = TransactionPhase.AFTER_COMMIT, fallbackExecution = true)
    public void saveToDB(UserOnlineEvent userRegisterEvent) {
        //更新用户信息
        User user = userRegisterEvent.getUser();
        User update = new User();
        update.setId(user.getId());
        update.setActiveStatus(ActiveStatusEnum.ONLINE.getStatus());
        update.setIpInfo(user.getIpInfo());
        update.setAvatar(update.getAvatar());
        update.setLastOptTime(update.getLastOptTime());
        userDao.updateById(update);
        //异步更新用户ip信息
        ipService.refreshIpDetailAsync(user.getId());
    }
}
